#include "cty_dat_parser.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <regex>

CTYDatParser::CTYDatParser() {
}

CTYDatParser::~CTYDatParser() {
}

bool CTYDatParser::loadFromFile(const std::string& filepath) {
    std::ifstream file(filepath);
    if (!file.is_open()) {
        last_error_ = "Failed to open file: " + filepath;
        return false;
    }
    
    countries_.clear();
    prefix_map_.clear();
    
    std::string line;
    CountryInfo current_info;
    std::vector<CountryInfo::AliasPrefix> current_aliases;
    std::string continued_line;
    
    while (std::getline(file, line)) {
        // 移除行尾的空格
        line.erase(line.find_last_not_of(" \t\r\n") + 1);
        
        // 跳过空行
        if (line.empty()) {
            continue;
        }
        
        // 处理续行（以逗号结尾的行）
        if (!continued_line.empty() || line.back() == ',') {
            if (!continued_line.empty()) {
                continued_line += " " + line;
            } else {
                continued_line = line;
            }
            
            // 如果当前行不以逗号结尾，说明续行结束
            if (line.back() != ',') {
                // 解析别名前缀
                current_aliases = parseAliasPrefixes(continued_line);
                addCountry(current_info, current_aliases);
                continued_line.clear();
            }
            continue;
        }
        
        // 处理注释行（以#开头的行）
        if (line[0] == '#') {
            continue;
        }
        
        // 检查是否是别名前缀行（以空格开头，后跟别名）
        if (line[0] == ' ' || line[0] == '\t') {
            // 这是别名前缀行
            current_aliases = parseAliasPrefixes(line);
            addCountry(current_info, current_aliases);
        } else {
            // 这是新的国家信息行
            if (parseLine(line, current_info)) {
                // 等待别名前缀行
            } else {
                last_error_ = "Failed to parse line: " + line;
                return false;
            }
        }
    }
    
    file.close();
    return true;
}

bool CTYDatParser::parseLine(const std::string& line, CountryInfo& info) {
    // 解析CTY.DAT格式的行
    // 格式: Country Name: CQ Zone: ITU Zone: Continent: Latitude: Longitude: UTC Offset: Primary Prefix:
    
    std::istringstream iss(line);
    std::string token;
    
    try {
        // 1. 国家名称 (到第一个冒号为止)
        std::getline(iss, info.country_name, ':');
        // 移除末尾的空格
        info.country_name.erase(info.country_name.find_last_not_of(" \t") + 1);
        
        // 检查是否在DARC WAEDC列表中（以*开头）
        info.is_waedc = false;
        if (!info.country_name.empty() && info.country_name.back() == '*') {
            info.is_waedc = true;
            info.country_name.pop_back();
            info.country_name.erase(info.country_name.find_last_not_of(" \t") + 1);
        }
        
        // 2. CQ Zone
        std::getline(iss, token, ':');
        info.cq_zone = std::stoi(token);
        
        // 3. ITU Zone
        std::getline(iss, token, ':');
        info.itu_zone = std::stoi(token);
        
        // 4. Continent
        std::getline(iss, token, ':');
        info.continent = token;
        info.continent.erase(0, info.continent.find_first_not_of(" \t"));
        info.continent.erase(info.continent.find_last_not_of(" \t") + 1);
        
        // 5. Latitude
        std::getline(iss, token, ':');
        info.latitude = std::stod(token);
        
        // 6. Longitude
        std::getline(iss, token, ':');
        info.longitude = std::stod(token);
        
        // 7. UTC Offset
        std::getline(iss, token, ':');
        info.utc_offset = std::stod(token);
        
        // 8. Primary Prefix
        std::getline(iss, info.primary_prefix, ';'); // 以分号结束
        info.primary_prefix.erase(0, info.primary_prefix.find_first_not_of(" \t"));
        info.primary_prefix.erase(info.primary_prefix.find_last_not_of(" \t") + 1);
        
        return true;
    } catch (const std::exception& e) {
        last_error_ = "Error parsing line: " + line + " - " + e.what();
        return false;
    }
}

std::vector<CountryInfo::AliasPrefix> CTYDatParser::parseAliasPrefixes(const std::string& prefixes_str) {
    std::vector<CountryInfo::AliasPrefix> aliases;
    
    // 移除前导空格
    std::string str = prefixes_str;
    str.erase(0, str.find_first_not_of(" \t"));
    
    // 按逗号分割
    std::istringstream iss(str);
    std::string prefix_part;
    
    while (std::getline(iss, prefix_part, ',')) {
        // 移除前后空格
        prefix_part.erase(0, prefix_part.find_first_not_of(" \t"));
        prefix_part.erase(prefix_part.find_last_not_of(" \t") + 1);
        
        if (prefix_part.empty()) {
            continue;
        }
        
        CountryInfo::AliasPrefix alias;
        
        // 检查是否需要精确匹配 (=)
        if (!prefix_part.empty() && prefix_part[0] == '=') {
            alias.exact_match = true;
            prefix_part = prefix_part.substr(1);
        }
        
        // 解析各种覆盖标记
        // 这里简化处理，实际实现可能需要更复杂的解析
        
        alias.prefix = prefix_part;
        aliases.push_back(alias);
    }
    
    return aliases;
}

void CTYDatParser::addCountry(const CountryInfo& info, const std::vector<CountryInfo::AliasPrefix>& aliases) {
    // 创建国家信息
    auto country = std::make_shared<CountryInfo>(info);
    country->aliases = aliases;
    
    // 添加到国家列表
    countries_[info.primary_prefix] = country;
    
    // 将主前缀添加到映射
    prefix_map_[info.primary_prefix] = country;
    
    // 将别名前缀添加到映射
    for (const auto& alias : aliases) {
        // 对于精确匹配的别名，我们只在精确匹配时使用
        if (!alias.exact_match) {
            prefix_map_[alias.prefix] = country;
        }
    }
}

const CountryInfo* CTYDatParser::lookupCountry(const std::string& callsign) const {
    // 提取可能的前缀
    auto prefixes = extractPossiblePrefixes(callsign);
    
    // 按长度降序排序，优先匹配较长的前缀
    std::sort(prefixes.begin(), prefixes.end(), [](const std::string& a, const std::string& b) {
        return a.length() > b.length();
    });
    
    // 查找匹配的前缀
    for (const auto& prefix : prefixes) {
        auto it = prefix_map_.find(prefix);
        if (it != prefix_map_.end()) {
            return it->second.get();
        }
    }
    
    return nullptr;
}

std::vector<std::string> CTYDatParser::extractPossiblePrefixes(const std::string& callsign) const {
    std::vector<std::string> prefixes;
    
    // 完整呼号
    prefixes.push_back(callsign);
    
    // 逐步缩短呼号，生成可能的前缀
    for (size_t i = callsign.length(); i > 0; --i) {
        prefixes.push_back(callsign.substr(0, i));
    }
    
    // 处理带斜杠的呼号 (例如: W1AW/P)
    size_t slash_pos = callsign.find('/');
    if (slash_pos != std::string::npos) {
        // 添加斜杠前的部分
        prefixes.push_back(callsign.substr(0, slash_pos));
        
        // 添加斜杠后的部分
        if (slash_pos + 1 < callsign.length()) {
            prefixes.push_back(callsign.substr(slash_pos + 1));
        }
    }
    
    return prefixes;
}

const std::map<std::string, std::shared_ptr<CountryInfo>>& CTYDatParser::getAllCountries() const {
    return countries_;
}